package com.authen.facecompare.extractfeaturn;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.SystemClock;
import android.util.Log;

import com.am.antispoof.RedSpoofAnti;
import com.am.fras.ConvertUtils;
import com.am.fras.FaceDetectResult;
import com.am.fras.FaceDetector;
import com.am.fras.FaceDetectorParam;
import com.am.fras.FaceExtractor;
import com.am.fras.PropDetector;
import com.authen.facecompare.activity.ModelInit;
import com.example.rizhaoscienceandtechnologymuseum.R;


/**
 * @author ylz
 * @Date 2016-09
 * @Description 人脸照离线抽特征
 * @File ExtractFeature.java
 */
public class ExtractFeature {
    private static final String TAG = "ExtractFeature";
    public static FaceDetector faceDetector = null;
    public static FaceExtractor faceExtractor = null;
    private static PropDetector propDetector=null;
    //public  static ColorSpoofAnti colorSpoofAnti=null;
    private static RedSpoofAnti redSpoofAnti = null;

    public static byte[] getFeatureOrCompare(Bitmap faceImage,Context cmx) {
        for (Integer in : ModelInit.modelDirMap.keySet()) {
            //map.keySet()返回的是所有key的值
            String str = ModelInit.modelDirMap.get(in);//得到每个key多对用value的值
            System.out.println(in + "     " + str);
        }
        if(faceDetector == null) {
            faceDetector = FaceDetector.createDetector(ModelInit.modelDirMap.get(R.raw.detect));
            FaceDetectorParam param = new FaceDetectorParam();
            param.scaleFactor = 0.0f;
            param.minObjSize = 10;
            param.deviceId = 0;
            param.stepFactor = 0.0f;
            faceDetector.setParam(param);
        }
        if(faceExtractor == null) {
            faceExtractor = FaceExtractor.createExtractor(ModelInit.modelDirMap.get(R.raw.extract));
        }
        Log.e(TAG, "===========face============" + ModelInit.modelDirMap.size());
        // 检测人脸
        byte[] feature = null;
        byte[] bgr = ConvertUtils.bitmapToBgrRotate(faceImage, ConvertUtils.ROTATE_TYPE_0);
        FaceDetectResult[] faceDetectResult1 = faceDetector.detectManyFaces(bgr, faceImage.getWidth(), faceImage.getHeight(), 1);
       Log.e(TAG, "================人脸检测:" + faceDetector + "   " + faceDetectResult1.length + "   " + R.raw.detect + "   " + ModelInit.modelDirMap.get(R.raw.detect));
        if (faceDetectResult1.length <= 0) {
            System.out.println("image1 has no face");
        } else {
            System.out.println("faceImage1 left: " + faceDetectResult1[0].left);
            System.out.println("faceImage1 top: " + faceDetectResult1[0].top);
            System.out.println("faceImage1 right: " + faceDetectResult1[0].right);
            System.out.println("faceImage1 bottom: " + faceDetectResult1[0].bottom);
        }
        if (faceDetectResult1 != null && faceDetectResult1.length > 0) {
            feature = faceExtractor.extractFeature(bgr, faceImage.getWidth(), faceImage.getHeight(), faceDetectResult1[0]);
            Log.e(TAG, "================人脸检测结果:" + faceDetectResult1[0].toString());
        }


        //质量检测
//        QualityEngine.initEngine(cmx, R.raw.quality);
//        QualityEngine.QualityResult qs=   QualityEngine.detectQuality(bgr,faceImage.getWidth(),faceImage.getHeight(),faceDetectResult1[0].landmarks);
//        Log.e(TAG, "============质量检测分数:" +qs.toString());
//
//        //属性检测
//        propDetector=PropDetector.createDetector(MainActivity.modelDirMap.get(R.raw.prop).toString());
//        if(propDetector!=null) {
//            PropResult propResult = propDetector.getPropResult(bgr, faceImage.getWidth(), faceImage.getHeight(), faceDetectResult1[0]);
//            Log.e(TAG, "============属性检测结果:" +propResult.toString());
//        }
//
//        //静默防伪检测
//        colorSpoofAnti=ColorSpoofAnti.createSpoofAnti(MainActivity.modelDirMap.get(R.raw.anticolor));
//        if(colorSpoofAnti!=null){
//         float colorResult=  colorSpoofAnti.getAntiScore(bgr, faceImage.getWidth(), faceImage.getHeight(), faceDetectResult1[0]);
//         Log.e(TAG, String.format(String.format(String.format(String.format("============静默检测结果:" + String.format("%.2f", colorResult))))));
//
//        }


        return feature;
    }

    public static float getCompareScore(byte[] featureTop, byte[] featureBottom) {
        if(faceExtractor == null) {
            faceExtractor = FaceExtractor.createExtractor(ModelInit.modelDirMap.get(R.raw.extract));
        }
        Log.e(TAG, "================分数检测:" + R.raw.extract + "   " + ModelInit.modelDirMap.get(R.raw.extract));
        Log.e(TAG, featureTop + " " + featureBottom);
        return faceExtractor.matchFeatures(featureTop, featureBottom) * 100;
    }
    public static byte[] getFeatureOrCompare(byte[] faceYUV, int width, int height, int rotate) {
//        for (Integer in : MainActivity.modelDirMap.keySet()) {
//            //map.keySet()返回的是所有key的值
//            String str = MainActivity.modelDirMap.get(in);//得到每个key多对用value的值
//            System.out.println(in + "     " + str);
//        }
        if(faceDetector == null) {
            faceDetector = FaceDetector.createDetector(ModelInit.modelDirMap.get(R.raw.detect));
            FaceDetectorParam param = new FaceDetectorParam();
            param.scaleFactor = 0.0f;
            param.minObjSize = 10;//30
            param.deviceId = 0;
            param.stepFactor = 0.0f;
            faceDetector.setParam(param);
        }
        if(faceExtractor == null) {
            faceExtractor = FaceExtractor.createExtractor(ModelInit.modelDirMap.get(R.raw.extract));
        }
        //Log.e(TAG, "===========face============" + MainActivity.modelDirMap.size());
        // 检测人脸
        long t1 = SystemClock.currentThreadTimeMillis();
        byte[] feature = null;
        //add by ljj 转移要90 270 要换宽高
        int irotate = ConvertUtils.ROTATE_TYPE_0;
        if(rotate == 90) irotate = ConvertUtils.ROTATE_TYPE_90;
        if(rotate == 180) irotate = ConvertUtils.ROTATE_TYPE_180;
        if(rotate == 270) irotate = ConvertUtils.ROTATE_TYPE_270;
        byte[] bgr = ConvertUtils.yuvToBgrRotate(faceYUV,width,height,irotate);
        FaceDetectResult[] faceDetectResult1 ;
        if(rotate == 90 || rotate == 270){
            faceDetectResult1 = faceDetector.detectManyFaces(bgr, height, width, 2);
        }else {
            faceDetectResult1 = faceDetector.detectManyFaces(bgr, width, height, 2);
        }
        Log.e(TAG, "================人脸检测:" + faceDetector + "   " + faceDetectResult1.length+
                " 耗时:"+(SystemClock.currentThreadTimeMillis()-t1)+"ms" );
                //+ "   " + R.raw.detect + "   " + MainActivity.modelDirMap.get(R.raw.detect)
        t1 = SystemClock.currentThreadTimeMillis();
        if (faceDetectResult1.length <= 0) {
            System.out.println("image1 has no face");
        } else {

            System.out.println("faceImage1 left: " + faceDetectResult1[0].left);
            System.out.println("faceImage1 top: " + faceDetectResult1[0].top);
            System.out.println("faceImage1 right: " + faceDetectResult1[0].right);
            System.out.println("faceImage1 bottom: " + faceDetectResult1[0].bottom);
        }
        if (faceDetectResult1 != null && faceDetectResult1.length > 0) {
            //寻找最宽人脸的下标
            float max = 0;
            int j = 0;
            for(int i = 0; i < faceDetectResult1.length; i++){
                if(max < (faceDetectResult1[i].right - faceDetectResult1[i].left)){
                    max = faceDetectResult1[i].right - faceDetectResult1[i].left;
                    j = i;
                    Log.e(TAG,"人脸"+j);
                }
            }

            //add by ljj 转移要90 270 要换宽高
            if(rotate == 90 || rotate == 270){
                feature = faceExtractor.extractFeature(bgr, height,width,  faceDetectResult1[j]);
            }else {
                feature = faceExtractor.extractFeature(bgr, width, height, faceDetectResult1[j]);
            }
            Log.e(TAG, "================人脸检测结果:" +" 耗时:"+(SystemClock.currentThreadTimeMillis()-t1)+"ms" );
            //+ faceDetectResult1[0].toString()
        }


        //质量检测
//        QualityEngine.initEngine(cmx, R.raw.quality);
//        QualityEngine.QualityResult qs=   QualityEngine.detectQuality(bgr,faceImage.getWidth(),faceImage.getHeight(),faceDetectResult1[0].landmarks);
//        Log.e(TAG, "============质量检测分数:" +qs.toString());
//
//        //属性检测
//        propDetector=PropDetector.createDetector(MainActivity.modelDirMap.get(R.raw.prop).toString());
//        if(propDetector!=null) {
//            PropResult propResult = propDetector.getPropResult(bgr, faceImage.getWidth(), faceImage.getHeight(), faceDetectResult1[0]);
//            Log.e(TAG, "============属性检测结果:" +propResult.toString());
//        }
//
//        //静默防伪检测
//        colorSpoofAnti=ColorSpoofAnti.createSpoofAnti(MainActivity.modelDirMap.get(R.raw.anticolor));
//        if(colorSpoofAnti!=null){
//         float colorResult=  colorSpoofAnti.getAntiScore(bgr, faceImage.getWidth(), faceImage.getHeight(), faceDetectResult1[0]);
//         Log.e(TAG, String.format(String.format(String.format(String.format("============静默检测结果:" + String.format("%.2f", colorResult))))));
//
//        }


        return feature;
    }


    public static RedSpoofAnti getRedSpoofAnti() {
        if(redSpoofAnti == null){
            redSpoofAnti = RedSpoofAnti.createSpoofAnti(ModelInit.modelDirMap.get(R.raw.anti));
        }
        return redSpoofAnti;
    }

    public static FaceDetector getFaceDetector() {
        if(faceDetector == null) {
            faceDetector = FaceDetector.createDetector(ModelInit.modelDirMap.get(R.raw.detect));
            FaceDetectorParam param = new FaceDetectorParam();
            param.scaleFactor = 0.0f;
            param.minObjSize = 10;//30
            param.deviceId = 0;
            param.stepFactor = 0.0f;
            faceDetector.setParam(param);
        }
        return faceDetector;
    }

//    public static PropDetector getPropDetector() {
//        if(propDetector == null) {
//            propDetector = PropDetector.createDetector(ModelInit.modelDirMap.get(R.raw.prop).toString());
//        }
//        return propDetector;
//    }

    public static FaceExtractor getFaceExtractor(){
        if(faceExtractor == null) {
            faceExtractor = FaceExtractor.createExtractor(ModelInit.modelDirMap.get(R.raw.extract));
        }
        return faceExtractor;
    }

    public static byte[] getFeatureOrCompareByBitmap(Bitmap bitmap,int width,int height,int rotate) {
        if(faceDetector == null) {
            faceDetector = FaceDetector.createDetector(ModelInit.modelDirMap.get(R.raw.detect));
            FaceDetectorParam param = new FaceDetectorParam();
            param.scaleFactor = 0.0f;
            param.minObjSize = 10;//30
            param.deviceId = 0;
            param.stepFactor = 0.0f;
            faceDetector.setParam(param);
        }
        if(faceExtractor == null) {
            faceExtractor = FaceExtractor.createExtractor(ModelInit.modelDirMap.get(R.raw.extract));
        }
        //Log.e(TAG, "===========face============" + MainActivity.modelDirMap.size());
        // 检测人脸
        long t1 = SystemClock.currentThreadTimeMillis();
        byte[] feature = null;
        //add by ljj 转移要90 270 要换宽高
        int irotate = ConvertUtils.ROTATE_TYPE_0;
        if(rotate == 90) irotate = ConvertUtils.ROTATE_TYPE_90;
        if(rotate == 180) irotate = ConvertUtils.ROTATE_TYPE_180;
        if(rotate == 270) irotate = ConvertUtils.ROTATE_TYPE_270;
        byte[] bgr = ConvertUtils.bitmapToBgrRotate(bitmap,irotate);
        FaceDetectResult[] faceDetectResult1 ;
        if(rotate == 90 || rotate == 270){
            faceDetectResult1 = faceDetector.detectManyFaces(bgr, height, width, 2);
        }else {
            faceDetectResult1 = faceDetector.detectManyFaces(bgr, width, height, 2);
        }
        Log.e(TAG, "================人脸检测:" + faceDetector + "   " + faceDetectResult1.length+
                " 耗时:"+(SystemClock.currentThreadTimeMillis()-t1)+"ms" );
        //+ "   " + R.raw.detect + "   " + MainActivity.modelDirMap.get(R.raw.detect)
        t1 = SystemClock.currentThreadTimeMillis();
        if (faceDetectResult1.length <= 0) {
            System.out.println("image1 has no face");
        } else {

            System.out.println("faceImage1 left: " + faceDetectResult1[0].left);
            System.out.println("faceImage1 top: " + faceDetectResult1[0].top);
            System.out.println("faceImage1 right: " + faceDetectResult1[0].right);
            System.out.println("faceImage1 bottom: " + faceDetectResult1[0].bottom);
        }
        if (faceDetectResult1 != null && faceDetectResult1.length > 0) {
            //add by ljj 转移要90 270 要换宽高
            if(rotate == 90 || rotate == 270){
                feature = faceExtractor.extractFeature(bgr, height,width,  faceDetectResult1[0]);
            }else {
                feature = faceExtractor.extractFeature(bgr, width, height, faceDetectResult1[0]);
            }
            Log.e(TAG, "================人脸检测结果:" +" 耗时:"+(SystemClock.currentThreadTimeMillis()-t1)+"ms" );
            //+ faceDetectResult1[0].toString()
        }
        return feature;
    }
}
